<template>
  <el-form :model="form" :label-width="labelWidth">
    <el-form-item :label="formItem.label">
      <el-autocomplete
        v-model="form[formItem.key]"
        :fetch-suggestions="querySearch"
        popper-class="my-autocomplete"
        v-bind="formItem.props"
        @select="handleSelect"
      >
        <template #default="{ item }">
          <div class="overflow-hidden w-full">
            <div class="value">{{ item.label }}</div>
            <span class="link inline-block truncate w-full">{{ item.value }}</span>
          </div>
        </template>
      </el-autocomplete>
      <el-alert
        v-if="formItem.tip"
        :title="formItem.tip"
        type="info"
        :closable="false"
        class="mt-1"
      />
    </el-form-item>
  </el-form>
</template>

<script setup>
import { onMounted, ref, reactive, watch } from 'vue'

const props = defineProps({
  items: {
    type: Array,
    default: () => []
  },
  labelWidth: {
    type: String,
    default: '70px'
  }
})

const formItem = ref(props.items[0])

// eslint-disable-next-line vue/require-prop-types
const model = defineModel({ default: () => ({}) })

// const emits = defineEmits(['submit'])

const form = reactive({})

watch(
  form,
  () => {
    Object.assign(model.value, form)
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => model.value,
  () => {
    Object.assign(form, model.value)
  },
  {
    deep: true,
    immediate: true
  }
)

const links = ref([])

const querySearch = (queryString, cb) => {
  const results = queryString ? links.value.filter(createFilter(queryString)) : links.value
  // call callback function to return suggestion objects
  cb(results)
}
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0 ||
      restaurant.label.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}
const loadAll = () => {
  return [...formItem.value.options]
}

// eslint-disable-next-line no-unused-vars
const handleSelect = (item) => {
  // console.log(item)
}

onMounted(() => {
  links.value = loadAll()
})
</script>

<style>
.my-autocomplete li {
  line-height: normal;
  padding: 7px;
  overflow: hidden;
}
.my-autocomplete li .name {
  text-overflow: ellipsis;
  overflow: hidden;
}
.my-autocomplete li .addr {
  font-size: 12px;
  color: #b4b4b4;
}
.my-autocomplete li .highlighted .addr {
  color: #ddd;
}
</style>
